<template>
    <div>
        <TableSearch :rp="rp" :options="searchOpt" :search="handleSearch" />
        <div class="container">

            <TableCustom  
                :columns="columns" 
                :tableData="tableData"
                :rp="rp"
                @update:rp="rp = $event"
                :query-data="queryDataApi"
                :del-data="deleteDataApi"
                :restore-data="restoreDataApi"
            >
                
                <!-- 表格上面的按钮 -->
                <template #toolbarBtn>
                    <el-button type="warning" :icon="CirclePlusFilled" @click="visible = true">新增</el-button>
                </template>
                
                <template #status="{ row }">
                    <el-tag type="success" v-if="row.status == 0">启用</el-tag>
                    <el-tag type="danger" v-else>禁用</el-tag>
                </template>

                <template #permissions="{ row }">
                    <el-button type="primary" size="small" plain @click="handlePermission(row)">管理</el-button>
                </template>

                 <!-- 操作 -->
                <template #operation="{ row, index }">
                    <el-button type="warning"  @click="handleView(row)">查看</el-button>
                    <el-button type="primary"  @click="handleEdit(row)">编辑</el-button>
                    <el-button type="danger"  @click="handleDelete(row)">删除</el-button>
                </template>
            </TableCustom>
        </div>
        <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="visible" width="700px" destroy-on-close
            :close-on-click-modal="false" @close="closeDialog">
            <TableEdit :form-data="rowData" :options="options" :edit="isEdit" :update="updateData" />
        </el-dialog>
        <el-dialog title="查看详情" v-model="visible1" width="700px" destroy-on-close>
            <TableDetail :data="viewData">
                <template #status="{ rows }">
                    <el-tag type="success" v-if="rows.status == 0">启用</el-tag>
                    <el-tag type="danger" v-else>禁用</el-tag>
                </template>
            </TableDetail>
        </el-dialog>
        <el-dialog title="权限管理" v-model="visible2" width="500px" destroy-on-close>
            <RolePermission :permiss-options="permissOptions" @close="handlePermissionClose"/>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="system-role">
import { ref, reactive } from 'vue';
import { ElMessage, rowProps } from 'element-plus';
import { Role } from '@/types/role';
import TableCustom from '@/components/table-custom.vue';
import TableDetail from '@/components/table-detail.vue';
import RolePermission from './components/role-permission.vue';
import TableEdit from '@/components/table-edit.vue';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import { FormOption, FormOptionList } from '@/types/form-option';
import {ajax } from '@/api';
import {RQ, initRQ, toQParams} from '@/types/rq';
import {RP} from '@/types/rp';
/************************* 控制变量 *******************************/
const tableData = ref<any[]>([]);

// 查询相关
const searchOpt = ref<FormOptionList[]>([
    { type: 'input', label: '角色名称：', prop: 'name' }
])

const rp = ref<RQ<any>>(initRQ());
rp.value.where = toQParams([
    { prop: 'status', type: 'eq', value: 0 },
]);

// 查看详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
    row: {},
    list: [],
    column: 1
});

// 权限管理弹窗相关
const visible2 = ref(false);
const permissOptions = ref({})

const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});

/************************* 配置 *******************************/

// 新增/编辑弹窗相关
const options = ref<FormOption>({
    labelWidth: '100px',
    span: 24,
    list: [
        { type: 'input', label: '角色名称', prop: 'name', required: true },
        { type: 'input', label: '角色标识', prop: 'roleKey', required: true },
        { type: 'switch', label: '状态', prop: 'status', required: false, activeText: '启用', inactiveText: '禁用', activeValue: 0, inactiveValue: -1 },
    ]
})

// 表格相关
let columns = ref([
    { type: 'index', label: '序号', width: 55, align: 'center' },
    { prop: 'name', label: '角色名称' },
    { prop: 'roleKey', label: '角色标识' },
    { prop: 'status', label: '状态' },
    { prop: 'permissions', label: '权限管理' },
    { prop: 'operation', width: 250,label: '操作'}
])

const handleView = (row: Role) => {
    viewData.value.row = { ...row }
    viewData.value.list = [
        {
            prop: 'id',
            label: '角色ID',
        },
        {
            prop: 'name',
            label: '角色名称',
        },
        {
            prop: 'roleKey',
            label: '角色标识',
        },
        {
            prop: 'status',
            label: '角色状态',
        },
    ]
    visible1.value = true;
};



/************************* 点击触发 *******************************/

// 更新数据插入数据
const updateData = (data: any) => {
    console.log("是否为编辑:"+isEdit);
    if( !isEdit.value ){
       addDataApi(data);
    }
    else{
       updateDataApi(data);
    }
};


// 搜索函数：触发分页重置到第一页
const handleSearch = () => {
   queryDataApi();
};


// 编辑
const handleEdit = (row: Role) => {
    rowData.value = { ...row };
    isEdit.value = true;
    visible.value = true;
};
// 关闭弹窗
const closeDialog = () => {
    visible.value = false;
    isEdit.value = false;
    rowData.value = {};
};
//点击管理时候触发
const handlePermission = (row: any) => {
    visible2.value = true;
    permissOptions.value = {
        id: row.id,
        permiss: JSON.parse(row.permiss)  || []
    };
}
// 处理权限管理弹窗关闭事件
const handlePermissionClose = () => {
    visible2.value = false;
    // 刷新数据
    queryDataApi();
};
/*************************  表格的封装方法 *******************************/
// 删除相关
const handleDelete = (data: Role) => {
    let ids = [data.id];
    deleteDataApi(ids);
}
/*************************  Api请求  *******************************/
// 从后端接口获取用户数据
const queryDataApi = async (queryRp?: RQ<any>) => {
    const currentRp = queryRp || rp.value;
    ajax({
        url: "role/list",
        method: 'POST', // 修正参数名称
        data: currentRp,
        success: (res) => {
            if( res.code == 0){
                tableData.value = res.dataList;
                // 更新 RP 中的总数
                rp.value.total = res.total;
            }else{
                ElMessage.error(res.msg);
            }
        }
    });

};

//添加数据
const addDataApi = async (data: any) => {
    ajax({
        url: "role/add",
        method: 'POST', // 修正参数名称
        data: data,
        success: (res) => {
            if( res.code == 0){
                ElMessage.success(res.msg);
                closeDialog(); 
                queryDataApi(); 
            }else{
                ElMessage.error(res.msg);
            }
        }
    });
};

//修改数据
const updateDataApi = async (data: any) => {
    ajax({
        url: "role/update",
        method: 'POST', // 修正参数名称
        data: data,
        success: (res) => {
            if( res.code == 0){
                ElMessage.success(res.msg);
                closeDialog(); // 关闭弹窗
                queryDataApi(); // 重新获取数据
            }else{
                ElMessage.error(res.msg);
            }
        }
    });
};

//删除数据
const deleteDataApi = async (ids?: number[]) => {
    if(ids){
        rp.value.ids = Array.isArray(ids) ? [...ids] : [ids];
    }
    ajax({
        url: "role/delete",
        method: 'POST', // 修正参数名称
        data: rp.value,
        success: (res) => {
            if( res.code == 0){
                ElMessage.success(res.msg);
                closeDialog(); // 关闭弹窗
                queryDataApi(); // 重新获取数据
            }else{
                ElMessage.error(res.msg);
            }
        }
    });
};
// 恢复数据
const restoreDataApi = async (ids?: number[]) => {
    if(ids){
        rp.value.ids = Array.isArray(ids) ? [...ids] : [ids];
    }
    ajax({
        url: "role/restore",
        method: 'POST', // 修正参数名称
        data: rp.value,
        success: (res:RP<any>) => {
            if( res.code == 0){
                ElMessage.success(res.msg);
                rp.value.ids = [];
                queryDataApi(); // 重新获取数据
            }else{
                ElMessage.error(res.msg);
            }
        }
    });
};

queryDataApi();
</script>

<style scoped></style>